package com.mdp.workflow.bus.candidate.strategy;

import com.mdp.core.err.BizException;
import com.mdp.core.utils.ObjectTools;
import com.mdp.core.utils.StrUtils;
import com.mdp.safe.client.entity.Dept;
import com.mdp.workflow.biz.ru.entity.ProcinstExpand;
import com.mdp.workflow.biz.ru.service.ProcinstExpandService;
import com.mdp.workflow.bus.candidate.TaskCandidateStrategy;
import com.mdp.workflow.client.service.WfSysUserService;
import com.mdp.workflow.comm.dict.CandidateStrategy;
import com.mdp.workflow.comm.dict.ProcinstConstants;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 9哥
 *
 *@author 唛盟开源9哥
 */
@Component
public class StartDeptLeaderStrategy implements TaskCandidateStrategy {

    @Autowired
    WfSysUserService wfSysUserService;

    @Lazy
    @Autowired
    ProcinstExpandService expandService;

    @Override
    public CandidateStrategy getStrategy() {
        return CandidateStrategy.START_DEPT_LEADER;
    }

    @Override
    public void validateParam(String param) {

    }

    @Override
    public Set<String> calculateUsers(DelegateExecution execution, String param) {
        String startDeptid= (String) execution.getTransientVariable(ProcinstConstants.START_DEPTID);
        if(ObjectTools.isEmpty(startDeptid)){
            ProcinstExpand expand=expandService.getProcinstExpandFirstCache(execution.getProcessInstanceId());
            if(expand==null){
                throw new BizException("no-way-to-find-start-deptid","没找到流程发起人归属部门");
            }
            startDeptid=expand.getDeptid();
        }
        Dept dept=wfSysUserService.getDept(startDeptid);
        if(dept==null){
            throw new BizException("dept-not-exists","部门%s不存在",startDeptid);
        }
        if(ObjectTools.isEmpty(dept.getLeader())){
            throw new BizException("dept-leader-not-set","部门%s未设置部门负责人",dept.getDeptName());
        }
        return StrUtils.splitToStringSet(dept.getLeader());
    }
 

    @Override
    public boolean isParamRequired() {
        return false;
    }



}
